package com.gk.aliyunocr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gk.aliyunocr.contants.OcrCotants;
import com.gk.aliyunocr.service.IdCardDiscernService;
import com.gk.aliyunocr.utils.FileUtils;
import com.gk.aliyunocr.utils.HttpUtils;
import com.gk.aliyunocr.utils.OrcApiUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 身份证信息扫描接口实现类
 */
@Service
public class IdCardDiscernServieImpl implements IdCardDiscernService {

    //@Value(value="${aliyun.ocr.url}")
    private String HOST;

    //@Value(value="${aliyun.ocrurl.idcard}")
    private String OCRIDCARDPATH;

    //@Value(value="${aliyun.appcode}")
    private String APPCODE;

    @Override
    /**
     * 身份证接口文本扫描
     */
    public String idCardDiscern(String path,String side) {
        try {
            // 调用阿里云文本识别所需的参数
            String host = HOST;
            String idCardPath = OCRIDCARDPATH;
            String appCode = APPCODE;
            String method = "POST";

            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization
            headers.put("Authorization", "APPCODE " + appCode);
            //根据API的要求，定义相对应的Content-Type
            headers.put("Content-Type", "application/json; charset=UTF-8");

            Map<String, String> querys = new HashMap<String, String>();
            // 封装身份证文本识别请求体
            String bodys = OrcApiUtils.reqIdCardBody(path,side);

            //请求调用阿里云接口
            try {
                HttpResponse response = HttpUtils.doPost(host, idCardPath, method, headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if(stat != 200){
                    System.out.println("Http code: " + stat);
                    System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                    System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                    return "请求失败";
                }

                String res = EntityUtils.toString(response.getEntity());
                JSONObject res_obj = JSON.parseObject(res);

                return res_obj.toJSONString();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
